package com.data.basic.chapter07;

import java.util.Map;

/**
 * Created by wangbing on 2018/5/15.
 */
public class LinkedListMap<K,V> implements MyMap<K,V> {

    private class Node<K,V>{// 链表节点的结构类   --->
        private K key;
        private V value;
        private Node next;

        public Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key) {
            this(key,null,null);
        }

        public Node() {
            this(null,null,null);
        }

        @Override
        public String toString() {
            return key.toString()+":"+value.toString();
        }
    }
    private Node dummyHead=new Node(null,null,null);
    private int size;


    public LinkedListMap() {
        dummyHead.next = null;
        size = 0;

    }

    public void add(K k, V v) {// 添加节点
        Node node = getNode(k);
        if (node==null){// 在链表头部插入节点
            dummyHead.next = new Node(k,v,dummyHead.next);
            size++;
        }
        else {// 重复元素更新
            node.value = v;
        }
    }

    public V remove(K k) {// 删除节点

        Node<K,V> node = getNode(k);

        if (node==null){
            throw  new IllegalArgumentException("删除的元素不存在！");
        }

        Node<K,V> cur = dummyHead.next;
        while(cur!=null){
            if (cur.next.equals(node)){
                cur.next = node.next;
                node.next = null;
                size--;
                return node.value;
            }
            cur = cur.next;
        }
        return null;
    }

    public boolean contains(K k) {// 是否包含节点

        return getNode(k)!=null;
    }

    public V get(K k) {//查询value
        return getNode(k)==null?null: getNode(k).value;

    }

    private Node<K,V> getNode(K key) {
        Node cur = dummyHead.next;
        while (cur!=null){
            if (cur.key.equals(key)){
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }

    public void set(K k, V v) {//根据键来设置map的值
        Node node = getNode(k);
        if (node==null){
            throw new IllegalArgumentException("key  doesn`t  exist!");
        }
        node.value = v;


    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size==0;
    }

    public static void main(String[] args) {
        LinkedListMap<Integer,String> linkedListMap = new LinkedListMap<Integer, String>();
        for (int i=0;i<10;i++){
            linkedListMap.add(i,String.valueOf(i));
        }
        for (int i=0;i<10;i++){
            System.out.println(linkedListMap.get(i));
        }
        System.out.println("-------------------");
        System.out.println("删除"+linkedListMap.remove(7));
        System.out.println("-------------------");

        for (int i=0;i<9;i++){
            System.out.println(linkedListMap.get(i));
        }

    }
}
